﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text; 

namespace MyBasicLib.Data.ORMLiteNew
{
    public abstract class DbQueryProvider : IDbQueryProvider 
    {
        internal protected abstract IDbCommand CreateCommand<TElement>(IDbQueryableInfo<TElement> dbQueryableInfo);

        public abstract IDatabase Executor { get; protected set; }

        public TElement Execute<TElement>(IDbQueryable<TElement> dbQueryable)   
        {
            var cmd = CreateCommand(dbQueryable);
            return Executor.Execute<TElement>(null,cmd);
        }

        public IList<TElement> ExecuteList<TElement>(IDbQueryable<TElement> dbQueryable)  
        {
            var cmd = CreateCommand(dbQueryable);
            return Executor.ExecuteList<TElement>(null, cmd).ToList();
        }

        public int ExecuteNonQuery<TElement>(IDbQueryable<TElement> dbQueryable)
        {
            var cmd = CreateCommand(dbQueryable);
            return Executor.ExecuteNonQuery(null, cmd);
        }

        private IDbCommand CreateCommand<TElement>(IDbQueryable<TElement> dbQueryable)
        {
            var dbQueryableInfo = DbQueryParser.Parse(dbQueryable);
            var cmd = CreateCommand(dbQueryableInfo);
            return cmd;
        }
        protected static System.Data.IDbDataParameter CreateParameter(string parameterToken, int idx, object parValue, int size = 0)
        {
            if (size == 0)
            {
                var parString = parValue as string;
                if (parString != null)
                {
                    if (parString.Length <= 36)
                        size = 36;
                    else if (parString.Length <= 100)
                        size = 100;
                    else if (parString.Length <= 1000)
                        size = 1000;
                    else if (parString.Length <= 4000)
                        size = 4000;
                }
            }
            return new System.Data.SqlClient.SqlParameter(parameterToken + "p" + idx,
                       parValue ?? DBNull.Value)
            {
                Size = size
            };
        }

         
    }
}
